package com.systop.ltbook.book.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.Query;
import org.hibernate.criterion.MatchMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.systop.cms.utils.PageUtil;
import com.systop.core.dao.support.Page;
import com.systop.core.service.BaseGenericsManager;
import com.systop.ltbook.BookConstants;
import com.systop.ltbook.book.model.Book;
import com.systop.ltbook.mainpage.MainPageAction;

/**
 * 图书管理类
 * 
 * @author DU
 * 
 */
@SuppressWarnings("unchecked")
@Service
public class BookManager extends BaseGenericsManager<Book> {

	/**
	 * 保存图书信息,并验证图书名称的唯一性
	 */
	@Transactional
	public void save(Book book) {
		/*
		 * if (StringUtils.isNotEmpty(book.getName())) { if
		 * (getDao().exists(book, "name")) { throw new
		 * ApplicationException("图书'" + book.getName() + "'已存在。"); } }
		 */

		super.save(book);
		MainPageAction.resetNewBooks();
		MainPageAction.resetHotBooks();
		MainPageAction.resetCheepBooks();
	}

	/**
	 * 删除图书信息，如存在封面照片则删除照片
	 * 
	 * @param book
	 *            图书
	 * @param realPath
	 *            封面照片地址
	 */
	@Transactional
	public void remove(Book book, String realPath) {
		if (book != null && StringUtils.isNotBlank(book.getCoverPhoto())) {
			File file = new File(realPath);
			if (file.exists()) {
				file.delete();
			}
		}
		super.remove(book);
	}

	/**
	 * 根据图书类型取得该类型的所有图书
	 * 
	 * @param bkType
	 *            图书类型
	 */
	public List<Map> getBooksByType(String bkType, int size) {
		return toMapArray(getByType(bkType, size));
	}

	public List<Book> getByType(String bkType, int size) {
		Page page = new Page(Page.start(1, size), size);
		StringBuffer hql = new StringBuffer("from Book bk where 1=1 ");
		List args = new ArrayList();
		// 按图书类型查询
		if (StringUtils.isNotBlank(bkType)) {
			hql.append(" and bk.bkType like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(bkType));
		}
		// 按图书ID排序
		hql.append(" order by bk.id desc");
		page = pageQuery(page, hql.toString(), args.toArray());
		return page.getData();
	}

	/**
	 * 将list中的对象转换为Map对象
	 * 
	 * @param list
	 * @return list of map
	 */
	private static List<Map> toMapArray(List<Book> list) {
		List<Map> result = new ArrayList(list.size());
		for (Book book : list) {
			Map item = new HashMap();
			item.put("bkId", book.getId());
			item.put("bkName", book.getName());
			item.put("bkPhoto", book.getCoverPhoto());
			item.put("author", book.getAuthor());
			item.put("price", book.getPrice());
			item.put("stock", book.getStock());
			result.add(item);
		}
		return result;
	}

	/**
	 * 根据图书类型查询图书信息
	 * 
	 * @param bkType
	 *            图书类型
	 * @param pressId
	 *            出版社ID
	 * @param pageSize
	 *            分页容量
	 * @param startIndex
	 *            起始行索引
	 */
	public List<Book> getBooksByType(String bkType, Integer pressId,
			Integer subjectId, String gradeId, int pageSize, int startIndex) {
		Page page = PageUtil.getPage(startIndex + 1, pageSize);
		List<Object> args = new ArrayList<Object>();
		StringBuffer hql = new StringBuffer("from Book bk where 1=1");
		// 按图书类型 (新书 热销 特价)
		if (StringUtils.isNotBlank(bkType)) {
			hql.append(" and bk.bkType like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(bkType));
		}
		// 按出版社
		if (pressId != null) {
			hql.append(" and bk.press.id = ?");
			args.add(pressId);
		}
		// 按学科
		if (subjectId != null) {
			hql.append(" and bk.subject.id = ?");
			args.add(subjectId);
		}
		// 按年级查询
		if (StringUtils.isNotBlank(gradeId)) {
			// 小学、初中、高中、考试
			if (gradeId.equals(BookConstants.GRADE_PRIMARY)
					|| gradeId.equals(BookConstants.GRADE_JUNIOR)
					|| gradeId.equals(BookConstants.GRADE_SENIOR)) {
				hql.append(" and bk.grade like ?");
				args.add(MatchMode.ANYWHERE.toMatchString(gradeId));
			} else {
				hql.append(" and bk.grade = ?");
				args.add(gradeId);
			}
		}

		// 按图书ID排序
		hql.append(" order by bk.id desc");
		page = getDao().pagedQuery(page, hql.toString(), args.toArray());

		return page.getData();
	}

	/**
	 * 根据图书类型查询符合条件的记录数量
	 * 
	 * @param bkType
	 *            图书类型
	 * @param pressId
	 *            出版社ID
	 * @return 符合条件的记录数量
	 */
	public int getBookCount(String bkType, Integer pressId, Integer subjectId,
			String gradeId) {
		StringBuffer hql = new StringBuffer("from Book bk where 1=1");
		List<Object> args = new ArrayList<Object>();
		// 按图书类型 (新书 热销 特价)
		if (StringUtils.isNotBlank(bkType)) {
			hql.append(" and bk.bkType like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(bkType));
		}
		// 按出版社
		if (pressId != null) {
			hql.append(" and bk.press.id = ?");
			args.add(pressId);
		}
		// 按学科
		if (subjectId != null) {
			hql.append(" and bk.subject.id = ?");
			args.add(subjectId);
		}
		// 按年级查询
		if (StringUtils.isNotBlank(gradeId)) {
			// 小学、初中、高中、考试
			if (gradeId.equals(BookConstants.GRADE_PRIMARY)
					|| gradeId.equals(BookConstants.GRADE_JUNIOR)
					|| gradeId.equals(BookConstants.GRADE_SENIOR)) {
				hql.append(" and bk.grade like ?");
				args.add(MatchMode.ANYWHERE.toMatchString(gradeId));
			} else {
				hql.append(" and bk.grade = ?");
				args.add(gradeId);
			}
		}
		return query(hql.toString(), args.toArray()).size();
	}
	
	public List<Book> getBooks(Integer size){
		Page page = PageUtil.getPage(1, size);
		String hql = "from Book b order by b.updateTime desc";
		page = pageQuery(page, hql);
		return page.getData();
	}
	
	/**
	 * 获取Top size books
	 * @param size
	 * @return
	 */
	public List<Book> getTopBooks(Integer size){
		String hql = "from Book b order by b.onTop desc, b.updateTime desc";
		Page page = PageUtil.getPage(1, size);
		page = pageQuery(page, hql);
		return page.getData();
	}

}
